﻿using System;
using System.IO;
using System.Web;

namespace SelArom.Net.Sitefinity.HttpModules
{
	/// <summary>
	/// HttpModule to take the public end of a Sitefinity website offline, leaving admin accessible
	/// </summary>
	public class OfflineModule : IHttpModule
	{
		private const string offlinePage = "/offline.aspx";

		#region IHttpModule Members

		public void Init(HttpApplication context)
		{
			context.PostAuthenticateRequest += context_PostAuthenticateRequest;
		}

		private void context_PostAuthenticateRequest(object sender, EventArgs e)
		{
			var context = HttpContext.Current;
			var request = context.Request.RawUrl.ToLower();

			// do not block admins
			// TODO: allow configuration of allowed users
			if (context.User.IsInRole("administrators")) return;

			// do not block sitefinity admin
			if (request.StartsWith("/sitefinity/login") || request.StartsWith("/sitefinity/admin")) return;

			// only check pages
			if (!request.EndsWith(".aspx") && request != "/") return;

			var siteOffline = File.Exists(context.Server.MapPath("/offline.true"));
			if (siteOffline)
			{
				// skip if user is already offline
				if (request == offlinePage) return;

				context.Response.Redirect(offlinePage, true);
				return;
			}

			// if we get to here, then we are online
			// if request is for offline page, redirect, otherwise just return
			if (request == offlinePage) context.Response.Redirect("/", true);
		}

		public void Dispose() { }

		#endregion
	}
}